/*
 * @Date: 2024-01-03 14:14:24
 * @LastEditors: lyx
 * @LastEditTime: 2024-01-03 14:14:42
 * @FilePath: \mt-middleware-server\src\gateway\websocket.ts
 * @Description:
 */
import * as ws from 'ws';

class messageWS {
  #websocket: any;
  #lockReconnect = false;
  #heartCheck: any;
  constructor(option: any) {
    this._createWebSocket(option);
  }
  _createWebSocket(option: any) {
    const {
      url,
      // eslint-disable-next-line @typescript-eslint/no-empty-function
      onmessage = (e: any) => {},
      // eslint-disable-next-line @typescript-eslint/no-empty-function
      onopen = (e: any) => {},
      // eslint-disable-next-line @typescript-eslint/no-empty-function
      onclose = (e: any) => {},
    } = option;
    this.#websocket = new ws(url);
    // eslint-disable-next-line @typescript-eslint/no-this-alias
    const that = this;
    this.#websocket.onopen = function (this: WebSocket, ev: Event) {
      // eslint-disable-next-line @typescript-eslint/no-this-alias
      const ws = this;
      const heartCheck = {
        timeout: 5000,
        timeoutObj: null,
        reset: function () {
          clearTimeout(this.timeoutObj);
          return this;
        },
        start: function () {
          this.timeoutObj = setInterval(function () {
            if (that.#websocket.readyState === 1) {
              console.log('连接状态，发送消息保持连接');
              ws.send(JSON.stringify({ type: 'ping' }));
              heartCheck.reset().start(); // 如果获取到消息，说明连接是正常的，重置心跳检测
            } else {
              console.log('ping 不到,断开状态了');
            }
          }, this.timeout);
        },
      };
      onopen({ handle: ws });
      heartCheck.reset().start();
      that.#heartCheck = heartCheck;
    };
    this.#websocket.onerror = function (this: WebSocket, ev: Event) {
      console.log('websocket.onerror==========', ev);
    };
    this.#websocket.onclose = function (e: any) {
      console.log(
        'websocket onclose: ' + e.code + ' ' + e.reason + ' ' + e.wasClean,
      );
      onclose({ handle: this });
    };
    // event 为服务端传输的消息，在这里可以处理
    this.#websocket.onmessage = function (event: any) {
      that.#heartCheck.reset().start();
      const { data } = event;
      onmessage({ handle: this.websocket, message: data });
      this.lockReconnect = true;
    };
  }
  _reconnect(option: any) {
    if (this.#lockReconnect) {
      return;
    }
    this.#lockReconnect = true;
    const unlock = () => {
      this.#lockReconnect = false;
    };
    const create = () => {
      this._createWebSocket(option);
    };
    setTimeout(function () {
      create();
      unlock();
    }, 4000);
  }
  close = () => {
    this.#heartCheck.reset();
    this.#websocket && this.#websocket.close();
  };
}

export { messageWS };
